"""Tag repository implementation (Synchronous)."""

from __future__ import annotations

from sqlalchemy.orm import Session
from sqlalchemy import func

from ..models.tag import Tag
from ..repositories.base import Repository
from ..schemas.tag import TagCreate, TagUpdate


class TagRepository(Repository[Tag, TagCreate, TagUpdate]):
    """Repository for Tag operations (Synchronous)."""

    def __init__(self, session: Session) -> None:
        super().__init__(Tag, session)

    def get_by_name(self, name: str) -> Tag | None:
        """根据标签名获取标签."""
        return self.session.query(Tag).filter(Tag.name == name).first()

    def get_by_category(self, category: str, skip: int = 0, limit: int = 100) -> list[Tag]:
        """根据分类获取标签列表."""
        return (
            self.session.query(Tag)
            .filter(Tag.category == category, Tag.is_active)
            .order_by(Tag.level.desc(), Tag.usage_count.desc())
            .offset(skip)
            .limit(limit)
            .all()
        )

    def get_by_level(self, level: int, skip: int = 0, limit: int = 100) -> list[Tag]:
        """根据优先级获取标签列表（从高到低）."""
        return (
            self.session.query(Tag)
            .filter(Tag.level == level, Tag.is_active)
            .order_by(Tag.usage_count.desc())
            .offset(skip)
            .limit(limit)
            .all()
        )

    def get_popular_tags(self, limit: int = 20) -> list[Tag]:
        """获取热门标签（按使用次数排序）."""
        return (
            self.session.query(Tag)
            .filter(Tag.is_active)
            .order_by(Tag.usage_count.desc(), Tag.level.desc())
            .limit(limit)
            .all()
        )

    def search_by_keyword(self, keyword: str, skip: int = 0, limit: int = 50) -> list[Tag]:
        """根据关键词搜索标签（name或keywords字段）."""
        search_pattern = f"%{keyword}%"
        return (
            self.session.query(Tag)
            .filter(
                Tag.is_active, (Tag.name.like(search_pattern) | Tag.keywords.like(search_pattern))
            )
            .order_by(Tag.level.desc(), Tag.usage_count.desc())
            .offset(skip)
            .limit(limit)
            .all()
        )

    def get_all_active(self, skip: int = 0, limit: int = 200) -> list[Tag]:
        """获取所有启用的标签（按优先级3→2→1，使用次数排序）."""
        return (
            self.session.query(Tag)
            .filter(Tag.is_active)
            .order_by(Tag.level.desc(), Tag.usage_count.desc())
            .offset(skip)
            .limit(limit)
            .all()
        )

    def increment_usage_count(self, tag_id: int) -> Tag | None:
        """增加标签使用次数."""
        tag = self.get(tag_id)
        if tag:
            tag.usage_count += 1
            self.session.flush()
            self.session.refresh(tag)
        return tag

    def get_statistics(self) -> dict[str, int | dict[str, int]]:
        """获取标签统计信息."""
        total = self.session.query(func.count(Tag.id)).scalar() or 0
        active = self.session.query(func.count(Tag.id)).filter(Tag.is_active).scalar() or 0

        by_category = {}
        for category in ["facility", "environment", "special", "custom"]:
            count = (
                self.session.query(func.count(Tag.id))
                .filter(Tag.category == category, Tag.is_active)
                .scalar()
                or 0
            )
            by_category[category] = count

        by_level = {}
        for level in [1, 2, 3]:
            count = (
                self.session.query(func.count(Tag.id))
                .filter(Tag.level == level, Tag.is_active)
                .scalar()
                or 0
            )
            by_level[f"level_{level}"] = count

        return {"total": total, "active": active, "by_category": by_category, "by_level": by_level}
